const {
    showSuccessToast,
    callContainerApi
} = require("../../utils/util");

Page({
    data: {
        addressList: [],
        showPrivacy: true,
        selectMode: false // 是否处于地址选择模式
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 检查是否处于选择模式
        if (options.selectMode === 'true') {
            this.setData({
                selectMode: true
            })
        }
    },


    async loadAddressList() {

        await callContainerApi('/address/address', "GET", null)
            .then(resu => {
                console.log(resu)
                const addressList = resu.data.data;
                this.setData({
                    addressList
                });
            })
    },
    onShow() {
        this.loadAddressList()
    },
    async setDefaultAddress(e) {
        const index = e.currentTarget.dataset.index
        await callContainerApi(`/address/setdefault?addressId=${this.data.addressList[index].id}`, "POST")
            .then(res => {
                console.log(res)
                const updateAddress = this.data.addressList
                updateAddress.forEach(a => a.top = 0)
                updateAddress[index].top = 1
                this.setData({
                    addressList: updateAddress
                })
                wx.showToast({
                    title: '设置默认地址成功',
                })
            })
    },
    deleteAddress(e) {
        const index = e.currentTarget.dataset.index
        const cur = this.data.addressList[index]
        console.log(cur)
        wx.showModal({
            title: '提示',
            content: '确定要删除该地址吗？',
            success: (res) => {
                if (res.confirm) {
                    callContainerApi(`/address/delete?addressId=${cur.id}&top=${cur.top || 0}`, "POST", null)
                    .then(ans => {
                        console.log(ans.data)
                        if (ans.data.status === 200) {
                            this.loadAddressList()
                        }
                    })
                }
            },
        })
    },
    addAddress() {
        wx.navigateTo({
            url: '/pages/addAddress/addAddress'
        });
    },

    selectAddress(e) {
        const {
            selectMode,
            addressList
        } = this.data
        if (!selectMode) {
            return
        }
        const index = e.currentTarget.dataset.index
        let cur = addressList[index]
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('selectAddressInfo', {
                data: cur
            }),
            wx.navigateBack()
    },

    // 编辑地址
    editAddress(e) {
        // 阻止冒泡，避免点击设为默认或删除按钮时触发编辑
        if (e.target.dataset.action === 'default' || e.target.dataset.action === 'delete') {
            return;
        }

        const index = e.currentTarget.dataset.index;
        const address = this.data.addressList[index];

        try {
            // 使用encodeURIComponent处理地址参数
            const params = {
                id: address.id,
                name: encodeURIComponent(address.receiveName),
                phone: address.phone,
                region: encodeURIComponent(address.region),
                address: encodeURIComponent(address.address),
                top: address.top,
                rank: address.rank,
                isEdit: true
            };

            const url = `/pages/addAddress/addAddress?${Object.entries(params)
                .map(([key, value]) => `${key}=${value}`)
                .join('&')}`;

            wx.navigateTo({
                url,
                fail: (err) => {
                    console.error('导航到编辑页面失败:', err);
                    wx.showToast({
                        title: '页面跳转失败',
                        icon: 'none'
                    });
                }
            });
        } catch (error) {
            console.error('处理地址数据失败:', error);
            wx.showToast({
                title: '操作失败，请重试',
                icon: 'none'
            });
        }
    }
});